<template>
   <div>
		  <editor
      v-model="conent"
      :init="initRichText"
      :disabled="disabled"
      :id="editorId"
      @input="handleInput"
			v-if="showRichText"
    ></editor>
		<upload v-show="false" 
			:uuid="uuid"
      :type="type"
      :domain="domain"
      :savePath="savePath"
			:config='config'
			ref="upload"
			@changefile="uploadChange"
			@error="uploadError"
		/>
	 </div>
</template>
<script>
import upload from '@/components/upload'

import tinymce from 'tinymce/tinymce';
import Editor from '@tinymce/tinymce-vue';
import 'tinymce/themes/silver';
import 'tinymce/icons/default/icons'; // 引入图标
import 'tinymce/plugins/image'; // 插入上传图片插件
import 'tinymce/plugins/media'; // 插入视频插件
import 'tinymce/plugins/table'; // 插入表格插件
import 'tinymce/plugins/lists'; // 列表插件
import 'tinymce/plugins/wordcount'; // 字数统计插件
import 'tinymce/plugins/print'; //打印
import 'tinymce/plugins/preview'; // 预览
import 'tinymce/plugins/autolink'; // 自动链接
import 'tinymce/plugins/help'; // 帮助
import 'tinymce/plugins/searchreplace'; // 查找替换
import 'tinymce/plugins/anchor'; // 锚点
import 'tinymce/plugins/insertdatetime'; // 日期
import 'tinymce/plugins/nonbreaking'; // 不间断空格
import 'tinymce/plugins/pagebreak'; // 插入分页符
import 'tinymce/plugins/paste'; // 粘贴符
import 'tinymce/plugins/toc'; // 目录生成器
import 'tinymce/plugins/visualblocks'; // 显示元素范围
import 'tinymce/plugins/codesample'; // 编辑事例
import 'tinymce/plugins/code'; // 编辑源码
import 'tinymce/plugins/directionality'; // 文字方向
import 'tinymce/plugins/fullpage'; // 文档属性
import 'tinymce/plugins/fullscreen'; // 全屏
import 'tinymce/plugins/hr'; // 水平分割线
import 'tinymce/plugins/link'; // 超链接
import 'tinymce/plugins/autoresize'; // 自动高度
import {baseURL,$uuid,subpath} from '@/util/util';
 export default {
    components: {
		Editor,upload
	},
	props: {
    disabled:{
      type: Boolean,
      default: true
    },
    value:{
      type: String,
      default: ''
    },
    height:{
      type: String,
      default: ''
    },
			// 本地上传  还是七牛上传
    type: {
      type: String,
      default: "",
    },
    // 唯一值
    uuid: {
      type: String,
      default: "",
    },
    // 域名
    domain: {
      type: String,
      default: "",
    },
		// 本地存储路径
		savePath: {
			type: String,
			default: ''
		},
		config:{
      type:Object,
      default:()=>{
        return {}
      }
    }
	},
	data() {
		return {
			conent:'',
			plugins:
				'lists advlist image media table wordcount preview print autolink help searchreplace advtable anchor insertdatetime nonbreaking pagebreak paste toc visualblocks codesample code directionality fullpage fullscreen hr link',
			initRichText: {
				language_url: subpath+'/tinymce/langs/zh_CN.js',
				language: 'zh_CN',
				skin_url: subpath+'/tinymce/skins/ui/oxide',
				selector: 'textarea',
				plugins:
					'lists advlist image media table wordcount preview print autolink help searchreplace advtable anchor insertdatetime nonbreaking pagebreak paste toc visualblocks codesample code directionality fullpage fullscreen hr link',
				paste_data_images: true,
				toolbar: 'formatselect toc visualblocks fullpage | bold italic forecolor backcolor nonbreaking pagebreak paste searchreplace| alignleft aligncenter alignright alignjustify hr ltr rtl anchor code codesample| bullist numlist outdent indent | insertdatetime lists link image media table | removeformat preview fullscreen print help',
				branding: false,
				menubar: 'file',
				images_upload_handler: (blobInfo, success, failure) => {
					if (blobInfo.blob().size / 1024 / 1024 > 10) {
						failure('上传失败，图片大小请控制在 10M 以内');
					} else {
						if (
							/gif|jpg|jpeg|png|svg|JPEG|GIF|JPG|PNG$/.test(blobInfo.filename().substring(blobInfo.filename().lastIndexOf('.') + 1, blobInfo.filename().length))
						) {
							this.uploadFile(blobInfo, success);
						} else {
							this.$message.error('图片格式为gif，jpg，jpeg，png');
							return;
						}
					}
				}
			},
      editorId: '',
			showRichText: false,
      suc: {},

		};
	},
	mounted() {
    
		tinymce.init({});
		this.showRichText = true
		this.conent = this.value;
	},
	created() {
		this.editorId = "RichText" + $uuid();
    this.initRichText.selector = "#" + this.editorId;

	  if (this.height && this.height.endsWith('px')) {
			this.initRichText.height = this.height;
		} else {
			delete this.initRichText.height;
			this.initRichText.plugins += ' autoresize';
		} 
	},
	methods: {
    handleInput(value){
      this.$emit('input', value)
    },
    dataURLtoBlob(baseurl) {
      let arr = baseurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime
      });
    },
		image2Base64(img) {
			var canvas = document.createElement('canvas');
			canvas.width = img.width;
			canvas.height = img.height;
			var ctx = canvas.getContext('2d');
			ctx.drawImage(img, 0, 0, img.width, img.height);
			let dataURL = canvas.toDataURL('image/jpeg', 0.9);
			if (dataURL.length > 1000000) {
				dataURL = canvas.toDataURL('image/jpeg', 0.1);
			} else if (dataURL.length > 500000) {
				dataURL = canvas.toDataURL('image/jpeg', 0.5);
			}
			return this.dataURLtoBlob(dataURL);
		},

		readImg(file) {
			return new Promise((resolve, reject) => {
				var img = new Image();
				const reader = new FileReader();
				reader.onload = e => {
					img.src = e.target.result;
				};
				reader.readAsDataURL(file);
				img.onload = () => {
					resolve(img);
				};
				img.onerror = e => {
					reject(e);
				};
			});
		},

		 /* 上传文件
     * @param {Blob} file 文件
     */
     
    async uploadFile(blobInfo, success) {
			this.suc = {
        fn: success,
      };
      const img = await this.readImg(blobInfo.blob())
      const file = this.image2Base64(img)
      file.name = blobInfo.filename()
      this.$refs.upload.uploadFile(true, file)
    },
    /* 上传失败 */
    uploadError(error) {
      console.log(error)
    },
    /* 上传成功 */
     /* 上传成功 */
    uploadChange(file) {
      this.suc.fn(file.url)
    },

			
	},
	watch: {
    conent(value) {
      this.$emit("update:value", value);
    },
		value(newValue) {
      this.conent = newValue;
    },
  },
}
</script>